import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { getTrainingList, getTrainingDetail, createTraining, updateTraining, deleteTraining, getTrainingCourses, getTrainingCourse, createTrainingCourse, updateTrainingCourse, deleteTrainingCourse, getMyTrainings, enrollTraining } from '../api/training'

// 培训计划相关异步操作
export const fetchTrainings = createAsyncThunk(
  'training/fetchTrainings',
  async (params, { rejectWithValue }) => {
    try {
      const response = await getTrainingList(params)
      return response
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '获取培训计划列表失败' })
    }
  }
)

export const fetchMyTrainings = createAsyncThunk(
  'training/fetchMyTrainings',
  async (params, { rejectWithValue }) => {
    try {
      const response = await getMyTrainings(params)
      return response
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '获取我的培训列表失败' })
    }
  }
)

export const fetchTrainingDetail = createAsyncThunk(
  'training/fetchTrainingDetail',
  async (id, { rejectWithValue }) => {
    try {
      const response = await getTrainingDetail(id)
      return response.data
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '获取培训计划详情失败' })
    }
  }
)

export const addTraining = createAsyncThunk(
  'training/addTraining',
  async (trainingData, { rejectWithValue }) => {
    try {
      const response = await createTraining(trainingData)
      return response.data
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '添加培训计划失败' })
    }
  }
)

export const editTraining = createAsyncThunk(
  'training/editTraining',
  async ({ id, data }, { rejectWithValue }) => {
    try {
      const response = await updateTraining(id, data)
      return response.data
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '更新培训计划失败' })
    }
  }
)

export const removeTraining = createAsyncThunk(
  'training/removeTraining',
  async (id, { rejectWithValue }) => {
    try {
      await deleteTraining(id)
      return id
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '删除培训计划失败' })
    }
  }
)

// 培训课程相关异步操作
export const fetchTrainingCourses = createAsyncThunk(
  'training/fetchTrainingCourses',
  async (params, { rejectWithValue }) => {
    try {
      const response = await getTrainingCourses(params)
      return response
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '获取培训课程列表失败' })
    }
  }
)

export const fetchTrainingCourseDetail = createAsyncThunk(
  'training/fetchTrainingCourseDetail',
  async (id, { rejectWithValue }) => {
    try {
      const response = await getTrainingCourse(id)
      return response.data
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '获取培训课程详情失败' })
    }
  }
)

export const addTrainingCourse = createAsyncThunk(
  'training/addTrainingCourse',
  async (courseData, { rejectWithValue }) => {
    try {
      const response = await createTrainingCourse(courseData)
      return response.data
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '添加培训课程失败' })
    }
  }
)

export const editTrainingCourse = createAsyncThunk(
  'training/editTrainingCourse',
  async ({ id, data }, { rejectWithValue }) => {
    try {
      const response = await updateTrainingCourse(id, data)
      return response.data
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '更新培训课程失败' })
    }
  }
)

export const removeTrainingCourse = createAsyncThunk(
  'training/removeTrainingCourse',
  async (id, { rejectWithValue }) => {
    try {
      await deleteTrainingCourse(id)
      return id
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '删除培训课程失败' })
    }
  }
)

// 培训报名相关异步操作
export const enrollToTraining = createAsyncThunk(
  'training/enrollToTraining',
  async ({ trainingId, data }, { rejectWithValue }) => {
    try {
      const response = await enrollTraining(trainingId, data)
      return response.data
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '培训报名失败' })
    }
  }
)

const initialState = {
  // 培训计划相关状态
  trainings: [],
  myTrainings: [],
  currentTraining: null,
  trainingPagination: {
    current: 1,
    pageSize: 10,
    total: 0
  },
  myTrainingPagination: {
    current: 1,
    pageSize: 10,
    total: 0
  },
  // 培训课程相关状态
  courses: [],
  currentCourse: null,
  coursePagination: {
    current: 1,
    pageSize: 10,
    total: 0
  },
  // 通用状态
  loading: false,
  error: null,
  // 统计数据
  statistics: {
    totalTrainings: 0,
    ongoingTrainings: 0,
    completedTrainings: 0,
    totalParticipants: 0
  }
}

const trainingSlice = createSlice({
  name: 'training',
  initialState,
  reducers: {
    clearError: (state) => {
      state.error = null
    },
    // 培训计划分页设置
    setTrainingCurrentPage: (state, action) => {
      state.trainingPagination.current = action.payload
    },
    setTrainingPageSize: (state, action) => {
      state.trainingPagination.pageSize = action.payload
    },
    setMyTrainingCurrentPage: (state, action) => {
      state.myTrainingPagination.current = action.payload
    },
    setMyTrainingPageSize: (state, action) => {
      state.myTrainingPagination.pageSize = action.payload
    },
    clearCurrentTraining: (state) => {
      state.currentTraining = null
    },
    // 培训课程分页设置
    setCourseCurrentPage: (state, action) => {
      state.coursePagination.current = action.payload
    },
    setCoursePageSize: (state, action) => {
      state.coursePagination.pageSize = action.payload
    },
    clearCurrentCourse: (state) => {
      state.currentCourse = null
    }
  },
  extraReducers: (builder) => {
    builder
      // 培训计划相关状态处理
      .addCase(fetchTrainings.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchTrainings.fulfilled, (state, action) => {
        state.loading = false
        state.trainings = action.payload.data || []
        state.trainingPagination.total = action.payload.total || 0
        if (action.payload.statistics) {
          state.statistics = {
            ...state.statistics,
            ...action.payload.statistics
          }
        }
      })
      .addCase(fetchTrainings.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '获取培训计划列表失败'
      })
      .addCase(fetchMyTrainings.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchMyTrainings.fulfilled, (state, action) => {
        state.loading = false
        state.myTrainings = action.payload.data || []
        state.myTrainingPagination.total = action.payload.total || 0
      })
      .addCase(fetchMyTrainings.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '获取我的培训列表失败'
      })
      .addCase(fetchTrainingDetail.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchTrainingDetail.fulfilled, (state, action) => {
        state.loading = false
        state.currentTraining = action.payload
      })
      .addCase(fetchTrainingDetail.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '获取培训计划详情失败'
      })
      .addCase(addTraining.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(addTraining.fulfilled, (state) => {
        state.loading = false
      })
      .addCase(addTraining.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '添加培训计划失败'
      })
      .addCase(editTraining.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(editTraining.fulfilled, (state) => {
        state.loading = false
      })
      .addCase(editTraining.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '更新培训计划失败'
      })
      .addCase(removeTraining.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(removeTraining.fulfilled, (state, action) => {
        state.loading = false
        state.trainings = state.trainings.filter(training => training.id !== action.payload)
      })
      .addCase(removeTraining.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '删除培训计划失败'
      })

      // 培训课程相关状态处理
      .addCase(fetchTrainingCourses.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchTrainingCourses.fulfilled, (state, action) => {
        state.loading = false
        state.courses = action.payload.data || []
        state.coursePagination.total = action.payload.total || 0
      })
      .addCase(fetchTrainingCourses.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '获取培训课程列表失败'
      })
      .addCase(fetchTrainingCourseDetail.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchTrainingCourseDetail.fulfilled, (state, action) => {
        state.loading = false
        state.currentCourse = action.payload
      })
      .addCase(fetchTrainingCourseDetail.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '获取培训课程详情失败'
      })
      .addCase(addTrainingCourse.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(addTrainingCourse.fulfilled, (state) => {
        state.loading = false
      })
      .addCase(addTrainingCourse.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '添加培训课程失败'
      })
      .addCase(editTrainingCourse.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(editTrainingCourse.fulfilled, (state) => {
        state.loading = false
      })
      .addCase(editTrainingCourse.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '更新培训课程失败'
      })
      .addCase(removeTrainingCourse.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(removeTrainingCourse.fulfilled, (state, action) => {
        state.loading = false
        state.courses = state.courses.filter(course => course.id !== action.payload)
      })
      .addCase(removeTrainingCourse.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '删除培训课程失败'
      })

      // 培训报名相关状态处理
      .addCase(enrollToTraining.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(enrollToTraining.fulfilled, (state) => {
        state.loading = false
      })
      .addCase(enrollToTraining.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '培训报名失败'
      })
  }
})

export const { 
  clearError, 
  setTrainingCurrentPage, 
  setTrainingPageSize, 
  setMyTrainingCurrentPage,
  setMyTrainingPageSize,
  clearCurrentTraining,
  setCourseCurrentPage,
  setCoursePageSize,
  clearCurrentCourse
} = trainingSlice.actions

export default trainingSlice.reducer